package com.server.chart;

import com.dao.chart.ChartsConfigMapper;
import com.dao.chart.ShowChartsMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.model.bo.*;
import com.model.pojo.RepCode;
import com.model.pojo.RepEntity;
import com.model.vo.configVo.HistogramConfigInfo;
import com.model.vo.dataVo.ChartsDataInfo;
import com.config.BasesSource.DynamicDataSourceContextHolder;
import com.util.CalculationJudgeUtil;
import com.util.ScreenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Repository
public class ShowHistogramService {
    @Autowired
    ShowChartsMapper showChartsMapper;
    @Autowired
    TimeConverterUtil timeConverterUtil;
    @Autowired
    CalculationJudgeUtil calculationJudgeUtil;
    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    GetChartsDataUtilService getChartsDataUtilService;
    @Autowired
    ScreenUtil screenUtil;
    @Autowired
    ChartsUtilService chartsUtilService;

    /*
    柱状图数据展示
     */
    public RepEntity showHistogram(HistogramConfigInfo histogramConfigInfo, String token, int dashId){
        ChartsDataInfo chartsDataInfo = new ChartsDataInfo();
        TimeReture timeReture = new TimeReture();
        if (histogramConfigInfo == null || "".equals(histogramConfigInfo)){
            return new RepEntity(RepCode.Null);
        }

        //取表名
        int id = histogramConfigInfo.getId();
        //获取列配置
        ChartsColumnConfig chartsColumn = chartsConfigMapper.getChartsColumn(id);
        if (chartsColumn == null || "".equals(chartsColumn)){
            return new RepEntity(RepCode.Null);
        }
        chartsDataInfo.setChartsColumnConfig(chartsColumn);

        String tableName = chartsUtilService.getSqlStr(token, id, dashId);
        if ("".equals(tableName)){
            return new RepEntity(RepCode.NoAuthority);
        }

        int baseId = getChartsDataUtilService.getBaseId(id);
        System.out.println("切换数据库"+baseId);

        try{
            if (!DynamicDataSourceContextHolder.isContainsDataSource(String.valueOf(baseId))) {
                //joinPoint.getSignature() ：获取连接点的方法签名对象
                System.out.println("数据源 " + baseId + " 不存在使用默认的数据源 -> ");
                return new RepEntity(RepCode.DataSourceNull);
            } else {
                System.out.println("使用数据源：" + baseId);
                DynamicDataSourceContextHolder.setDataSourceType(String.valueOf(baseId));
            }

            String xColumn = histogramConfigInfo.getxAxis().getColumnRename();
            String yColumn = histogramConfigInfo.getyAxis().getColumnRename();
            String xColumnType = histogramConfigInfo.getxAxis().getColumnType();

            String xAxisType = histogramConfigInfo.getxAxis().getShowDataType();
            List<String> groupBy = histogramConfigInfo.getGroups();

            if (xColumn == null || "".equals(xColumn) || yColumn == null || "".equals(yColumn)){
                return new RepEntity(RepCode.nullAxis);
            }

            String yType = histogramConfigInfo.getyAxis().getShowDataType();
            String yAxisType = calculationJudgeUtil.Judge(yType);


            Series series = new Series();
            List<Double> value = new ArrayList<Double>();
            List<Series> serieses = new ArrayList<Series>();    //生成柱状图的系列
            List<String> xAxisData = new ArrayList<String>();  //X轴自己用
            List<String> xData = new ArrayList<String>();      //X轴前端用

            //取筛选列表
            List<Screen> screens = histogramConfigInfo.getFilters();
            ScreenStr scr = new ScreenStr();
            String screen = "";               //正常筛选条件
            String screenToColumn = "";       //跟目标列相同的筛选条件
            String screenToColumnS = "";       //跟目标列相同的筛选条件
            if ("".equals(screens) || screens == null || screens.size() == 0){
                screen = "";
            }else {
                scr = screenUtil.screensUtil(screens, xColumn, xColumnType);
                screen = scr.getRet();
                screenToColumn = scr.getWithColumnRet();
                StringBuilder sb = new StringBuilder(screenToColumn);
                System.out.println("sb:"+sb);
                if (screenToColumn != null && !("".equals(screenToColumn))){
                    screenToColumnS = screenToColumn + " " + screen;               //and
                    screenToColumn = String.valueOf(sb .replace(1, 5, "where "));
                    screen = screenToColumn + " " + screen;         //where
                    System.out.println("screen:" + screen);
                } else {
                    StringBuilder sb1 = new StringBuilder(screen);
                    screenToColumnS = screen;
                    screen = String.valueOf(sb1 .replace(1, 5, "where "));
                }
            }

            //X轴
            //判断是否为日期类型
            if ("time".equals(xColumnType)){
                timeReture = timeConverterUtil.timeConverter(xColumn, tableName, xAxisType, screen, 20);
                xAxisData = timeReture.getValues();
                chartsDataInfo.setTooMany(timeReture.isOverdose());
                System.out.println("xA:" + xAxisData);
                xData = timeConverterUtil.toRespons(xAxisData,xAxisType );
                System.out.println("data:"+xAxisData);
            }else {
                int count = showChartsMapper.getNumForX(xColumn, tableName);
                if (count > 20){
                    chartsDataInfo.setTooMany(true);
                }
                xAxisData = showChartsMapper.getXAxis(xColumn, tableName, screen, 20);

            }
            if ("".equals(xAxisData) || xAxisData == null || xAxisData.size() == 0){
                return new RepEntity(RepCode.Null);
            }
            if ("week".equals(xAxisType) || "month".equals(xAxisType) || "quarter".equals(xAxisType)){
                chartsDataInfo.setxAxis(xData);
            }else {
                chartsDataInfo.setxAxis(xAxisData);
            }

            //无分组时Y值
            Iterator itX = xAxisData.iterator();
            while (itX.hasNext()){
                String xdata = (String)itX.next();
                double valueOne = 0;
                String valueOnes = null;
                if ("time".equals(xColumnType)){
                    valueOnes = timeConverterUtil.getTimeValueConverter(yColumn, xColumn, tableName, yAxisType, xAxisType, xdata, screenToColumnS);
                }else {
                    if (xdata == null || "".equals(xdata)){
                        valueOnes = showChartsMapper.getValuesIsNull(yColumn, xColumn, tableName, yAxisType, screenToColumnS);
                    }else {
                        valueOnes = showChartsMapper.getValues(yColumn, xColumn, tableName, yAxisType, xdata, screenToColumnS);
                    }
                }
                if (valueOnes == null || "".equals(valueOnes)){
                    valueOne = 0;
                }else {
                    valueOne = Double.parseDouble(valueOnes);
                }
                value.add(valueOne);
            }

            System.out.println(value);
            series.setName(xColumn);
            series.setValue(value);
            serieses.add(series);
            System.out.println(serieses);

            //有分组
            if (groupBy.size() != 0){
                serieses.remove(0);
                Iterator itGroup = groupBy.iterator();  //分组数

                //便利分组
                while (itGroup.hasNext()){
                    String groupByName = (String) itGroup.next(); //每个分组的组名
                    int counts = showChartsMapper.getGroupsCount(groupByName,tableName, screenToColumnS);
                    if (counts > 20){
                        chartsDataInfo.setTooMany(true);
                    }
                    List<String> groupsData = showChartsMapper.getGroups(groupByName,tableName, screenToColumnS, 20); //查询每个分组系列
                    System.out.println("groupdata:"+ groupsData.toString());
                    Iterator itGroupsData = groupsData.iterator();

                    //每个分组得到得每个系列
                    while(itGroupsData.hasNext()){
                        Series ne = new Series();
                        String groupsName = (String)itGroupsData.next();
                        ne.setName(groupsName);
                        ne.setStack(groupByName);

                        List<Double> groupsValue = new ArrayList<Double>();
                        Iterator itXAxisData = xAxisData.iterator();

                        //每个系列对应X轴上的值
                        while (itXAxisData.hasNext()){
                            String xAxisDataOne = (String) itXAxisData.next();
                            double groupsValueOne = 0;
                            String groupsValueOnes = null;
                            if ("time".equals(xColumnType)){
                                groupsValueOnes = timeConverterUtil.getGroupTimeConverter(yAxisType, yColumn, tableName, groupByName, xAxisType,
                                        groupsName, xColumn, xAxisDataOne, screenToColumnS);
                            }else {
                                String xColumnKey = "";
                                if (xAxisDataOne == null || "".equals(xAxisDataOne)){
                                    xColumnKey  = xColumn + " is null";
                                }else
                                {
                                    xColumnKey = xColumn + " = '" +xAxisDataOne +"'";
                                }

                                String groupByKey = "";
                                if (groupsName == null || "".equals(groupsName)){
                                    groupByKey = groupByName +" is null";
                                }else {
                                    groupByKey = groupByName + " = '" +groupsName +"'";
                                }
                                groupsValueOnes = showChartsMapper.getGroupsValue(yAxisType, yColumn, tableName, groupByKey, xColumnKey, screenToColumnS);
                            }
                            if ("".equals(groupsValueOnes) || groupsValueOnes == null){
                                groupsValueOne = 0;
                            }else{
                                groupsValueOne = Double.parseDouble(groupsValueOnes);
                            }
                            groupsValue.add(groupsValueOne);
                        }

                        ne.setValue(groupsValue);
                        System.out.println("值："+ series);
                        serieses.add(ne);
                    }
                    System.out.println(serieses);
                }
            }

            chartsDataInfo.setSerieses(serieses);
        }catch (Exception e){
        e.printStackTrace();
        System.out.println("异常");
        return new RepEntity(RepCode.erro);
    }finally {
            System.out.println("关闭数据源");
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

        return new RepEntity(RepCode.success, chartsDataInfo);
    }


}
